import { onMounted, ref, watch } from "vue";
import {
  addDepartmentList,
  addMonitors,
  delDepartment,
  delMonitors,
  editDepartment,
  editMonitors,
  getAreasList,
  getCompetencesList,
  getDepartmentsList,
  getDepartmentsMonitors,
  getMonitorData,
  getPositionsList,
} from "../../api/system/department-settingApi";
import { ElMessage, ElMessageBox } from "element-plus";
import { checkPhone } from "../../utils";

export default function DepartmentSetting() {
  const treeData = ref([]);
  //获取部门节点数据
  function getDepartment() {
    getDepartmentsList().then((res) => {
      treeData.value = res.data;
    });
  }
  //顶部新增对话框
  const addChildDialogVisible = ref(false);
  //顶部新增数据表单
  const addForm = ref({});
  //顶部新增对话框标识
  const addNodeRef = ref(null);
  //顶部新鞋子表单验证规则
  const addNodeRules = ref({
    name: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  });
  //新增部门节点
  function addDepartments() {
    addChildDialogVisible.value = true;
  }
  //提交新增部门节点操作
  function submitDepartment() {
    addNodeRef.value.validate((valid) => {
      if (valid) {
        addDepartmentList({
          name: addForm.value.name,
          parentId: 0,
          sort: treeData.value.length + 1,
        }).then(() => {
          ElMessage.success("添加部门成功");
          addNodeRef.value.resetFields();
          addChildDialogVisible.value = false;
          getDepartment();
        });
      }
    });
  }
  //搜索过滤数据
  const filterText = ref("");
  //树形标识
  const treeRef = ref(null);
  onMounted(() => {
    getDepartment();
  });
  watch(filterText, (val) => {
    treeRef.value.filter(val);
  });
  //过滤方法
  function filterNode(value, data) {
    if (!value) return true;
    return data.name.indexOf(value) !== -1;
  }
  //添加部门子节点
  const nodeAddDialogVisible = ref(false);
  const nodeId = ref("");
  const nodeAddForm = ref({});
  const nodeRef = ref(null);
  function addNode(data) {
    nodeAddDialogVisible.value = true;
    nodeAddForm.value.parentName = data.name;
    nodeId.value = data.id;
  }
  //提交新增节点操作
  function submitAddNode() {
    addDepartmentList({
      name: nodeAddForm.value.name,
      parentId: nodeId.value,
      sort: 1,
    }).then(() => {
      ElMessage.success("添加子部门成功");
      nodeRef.value.resetFields();
      nodeAddDialogVisible.value = false;
      getDepartment();
    });
  }
  //编辑节点操作
  const sort = ref("");
  const editNodeRef = ref(null);
  const nodeEditDialogVisible = ref(false);
  const editNodeForm = ref({});
  function editNode(data, node) {
    nodeEditDialogVisible.value = true;
    editNodeForm.value.parentName = node.parent.data.name;
    editNodeForm.value.name = data.name;
    sort.value = data.sort;
    nodeId.value = data.id;
  }
  //提交编辑节点操作
  function submitEditNode() {
    editDepartment(nodeId.value, {
      name: editNodeForm.value.name,
      sort: sort.value,
    }).then(() => {
      ElMessage.success("修改部门成功");
      nodeEditDialogVisible.value = false;
      editNodeRef.value.resetFields();
      getDepartment();
    });
  }
  //删除节点操作
  function delNode(data) {
    ElMessageBox.confirm("您确定要删除这条数据么？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        delDepartment(data.id).then(() => {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getDepartment();
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消操作",
        });
      });
  }
  const checkedId = ref("");
  const pageNum = ref(1);
  const pageSize = ref(5);
  const totalNum = ref("");
  const tableData = ref([]);
  //实现复选框单选
  function handleNodeClick(data, checked) {
    if (checked.checkedKeys !== "") {
      checkedId.value = data.id;
      treeRef.value.setCheckedKeys([data.id], true);
      getMonitors();
    } else {
      treeRef.value.setCheckedKeys([]);
    }
  }
  //通过id获取部门负责人
  function getMonitors() {
    getDepartmentsMonitors(checkedId.value, {
      pageNumber: pageNum.value,
      pageSize: pageSize.value,
    }).then((res) => {
      tableData.value = res.data.content;
      totalNum.value = res.data.totalElements;
    });
  }
  //表格新增操作
  const tableDialogVisible = ref(false);
  const tableForm = ref({});
  const tableRef = ref(null);
  const nameOption = ref([]);
  const jobOption = ref([]);
  const znOption = ref([]);
  const areaOption = ref([]);
  const userId = ref("");
  const areaList = ref([]);
  const dialogTile = ref("");
  function addTableData(row) {
    dialogTile.value = "新增";
    if (!checkedId.value) {
      ElMessage.warning("请先选择部门后再操作");
    } else {
      tableDialogVisible.value = true;
      //  获取姓名
      getMonitorData().then((res) => {
        nameOption.value = res.data.content;
      });
      //  获取职位
      getPositionsList().then((res) => {
        jobOption.value = res.data.content;
      });
      //  获取职能
      getCompetencesList().then((res) => {
        znOption.value = res.data.content;
      });
      // 获取区域
      getAreasList(0).then((res) => {
        areaOption.value = res.data;
      });

      if (row !== undefined) {
        dialogTile.value == "编辑";
        userId.value = row.id;
        tableForm.value.name = row.userId;
        tableForm.value.mobile = row.mobile;
        tableForm.value.job = row.positionId;
        tableForm.value.zn = row.competenceId;
        tableForm.value.area = row.areaId;
        tableForm.value.principal = row.principal;
      }
    }
  }
  //提交表格新增编辑数据
  function submitMonitors() {
    tableRef.value.validate((valid) => {
      if (valid) {
        if (!userId.value) {
          addMonitors(checkedId.value, {
            userId: tableForm.value.name,
            areaId: tableForm.value.area,
            competenceId: tableForm.value.zn,
            positionId: tableForm.value.job,
            principal: tableForm.value.principal,
          }).then(() => {
            ElMessage.success("添加部门成功");
            tableDialogVisible.value = false;
            tableRef.value.resetFields();
            getMonitors();
          });
        } else {
          editMonitors(userId.value, {
            userId: tableForm.value.name,
            areaId: tableForm.value.area,
            competenceId: tableForm.value.zn,
            positionId: tableForm.value.job,
            principal: tableForm.value.principal,
          }).then(() => {
            ElMessage.success("修改部门成功");
            tableDialogVisible.value = false;
            tableRef.value.resetFields();
            getMonitors();
          });
        }
      }
    });
  }
  //删除表格数据
  function delTableData(id) {
    ElMessageBox.confirm("您确定要删除这条数据么？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        delMonitors(id).then(() => {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getMonitors();
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消操作",
        });
      });
  }
  //级联选择器方法
  function handleCascaderChange(val) {
    areaList.value = val;
  }
  //表单验证规格
  const rules = ref({
    mobile: [{ validator: checkPhone, trigger: "blur" }],
    name: [{ required: true, message: "请选择姓名", trigger: "blur" }],
    job: [{ required: true, message: "请选择职位", trigger: "blur" }],
    zn: [{ required: true, message: "请选择职能", trigger: "blur" }],
    area: [{ required: true, message: "请选择区域", trigger: "blur" }],
  });
  return {
    addNodeRules,
    handleCascaderChange,
    dialogTile,
    areaList,
    rules,
    delTableData,
    submitMonitors,
    areaOption,
    znOption,
    jobOption,
    nameOption,
    addTableData,
    tableRef,
    tableDialogVisible,
    tableForm,
    treeData,
    addDepartments,
    addForm,
    addChildDialogVisible,
    submitDepartment,
    addNodeRef,
    filterText,
    treeRef,
    filterNode,
    addNode,
    nodeAddDialogVisible,
    nodeAddForm,
    submitAddNode,
    nodeRef,
    nodeEditDialogVisible,
    editNodeForm,
    submitEditNode,
    editNode,
    editNodeRef,
    delNode,
    handleNodeClick,
    pageNum,
    pageSize,
    totalNum,
    getMonitors,
    tableData,
  };
}
